package Array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class item18 {
    public static List<List<Integer>> fourSum(int[] nums, int target) {


        if(nums.length<4||nums==null)
        {
            return new ArrayList<>();
        }
        Boolean flag1 = false;
        Boolean flag =false;

        Arrays.sort(nums);
        int sum =2000000000;
        //这个要求只要对应坐标不同就行
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i <=nums.length-4 ; i++) {
            if(i!=0&&nums[i-1]==nums[i])continue;
            for (int j = i+1; j<=nums.length-3 ; j++) {
                if(j>i+1&&nums[j]==nums[j-1])continue;
                int L =j+1;
                int R = nums.length-1;

                while (L<R)
                {
                    sum = nums[i]+nums[j]+nums[L]+nums[R];
                    if(sum==target)
                    {   flag1 = true;
                        res.add(Arrays.asList(nums[i],nums[j],nums[L],nums[R]));
                        while(L<R&&nums[L]==nums[L+1])L++;
                        while(L<R&&nums[R]==nums[R-1])R--;
                        L++;
                        R--;
                    }
                    else if(sum<target)
                    {
                        L++;
                    }
                    else {
                        R--;
                    }
                }
            }
        }
        if(flag1==false)
        {
            return new ArrayList<>();
        }else {
            return res;
        }

    }

    public static void main(String[] args) {
//        [-2,-1,-1,1,1,2,2]
//        0
//        [0,0,0,0]
//        0
        int [] nums = {0,0,0,0};
        List ls = fourSum(nums,0);
        System.out.println(ls);
    }
}
